/* eslint-disable @typescript-eslint/no-explicit-any */
import React, { useEffect, useRef, useState } from "react";
import "./index.less";
import NavBar from "../../components/NavBar";
import { useSearchParams } from "react-router-dom";
import {
  bookSite,
  commentPostAnswer,
  commentRoom,
  getPostComment,
  getRoom,
  getRoomSites,
  getSignInfo,
  removeOwnComment,
  userSign,
} from "../../server/api";
import { COMURL } from "../../constant";
import { IRoomDetails, IRoomSiteDetails } from "./type";
import { Button, Popconfirm, message } from "antd";
import BookingSiteForm from "../BookingSiteForm";
import Review from "../../components/Review";
const RoomDetails: React.FC = () => {
  const [searchParam] = useSearchParams();
  const [room, setRoom] = useState<IRoomDetails>({} as IRoomDetails);
  const [roomSite, setRoomSite] = useState<IRoomSiteDetails[]>();
  const [isOpen, setIsOpen] = useState(false);
  const [date, setDate] = useState<string[]>();
  const [siteId, setSiteId] = useState(0);
  const [reviewList, setReviewList] = useState<[]>([]);
  const [reviewCtn, setReviewCtn] = useState<string>("");
  const [reviewParams, setReviewPrams] = useState({
    roomId: 0,
    userId: 0,
    rootId: 0,
  });
  const [isBook, setIsBook] = useState(false);
  const textareaRef = useRef<any>(null);
  const textRef = useRef<any>(null);
  const [signId, setSignId] = useState(0);
  const getRoomDetail = async () => {
    const roomData: any = await getRoom({
      roomName: searchParam.get("roomName"),
    });

    setRoom(roomData.records[0]);
    getRooSiteDetail(roomData?.records[0]?.id || []);
  };
  const getRooSiteDetail = async (siteId: number) => {
    const roomSiteData: any = await getRoomSites({
      roomId: siteId,
    });
    const newarr = roomSiteData.sort(
      (a: any, b: any) => a.siteNumber - b.siteNumber
    );
    setRoomSite(newarr);
  };
  const getRoomSiteStatus = (value: number) => {
    if (value === 1) {
      return "burlywood";
    } else if (value === 0) {
      return "aqua";
    } else return "burlywood";
  };
  const onCancel = () => {
    setDate([]);
    setIsOpen(false);
  };
  const onConfirm = async () => {
    await bookSite({
      endTime: date?.[1],
      startTime: date?.[0],
      id: siteId,
    });
    await getRoomDetail();
    message.success("预约成功");
    setIsOpen(false);
    setDate([]);
  };
  const changeDate = (date: any, dateString: any) => {
    setDate(dateString);
  };
  const handleIsBookingSite = (id: number) => {
    setSiteId(id);
    setIsOpen(true);
  };
  // 评论区
  const handleChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    setReviewCtn?.(e.target.value);
  };
  const onPublish = async () => {
    if (reviewParams.rootId) {
      await commentPostAnswer({
        content: reviewCtn,
        replyUserId: reviewParams.userId,
        roomId: reviewParams.roomId,
        rootId: reviewParams.rootId,
      });
      setReviewCtn("");
      message.success("回复成功");
    } else {
      await commentRoom({
        content: reviewCtn,
        roomId: parseInt(searchParam.get("roomId") as string),
      });
      setReviewCtn("");
      message.success("评论成功");
    }
    setReviewPrams({ ...reviewParams, roomId: 0, userId: 0, rootId: 0 });
    getReview();
  };
  const handleReply = (roomId: number, userId: number, rootId: number) => {
    textareaRef.current.focus();
    textRef.current.scrollIntoView({ behavior: "smooth", block: "center" });
    setReviewPrams({ roomId, userId, rootId });
  };
  const handleDel = async (id: number) => {
    await removeOwnComment({ commentId: id });
    message.success("删除成功");
    getReview();
  };
  const getReview = async () => {
    const reviewData: any = await getPostComment({
      roomId: parseInt(searchParam.get("roomId") as string),
    });
    setReviewList(reviewData);
  };
  const handleIsBook = (room: any) => {
    if (!room || !room.openTime || !room.closeTime) {
      console.warn("Room data is not available yet.");
      return;
    }
    const now = new Date();
    const [startHour, startMinute, startSecond] = room.openTime
      .split(":")
      .map(Number);
    const [endHour, endMinute, endSecond] = room.closeTime
      .split(":")
      .map(Number);
    const startDate = new Date();
    startDate.setHours(startHour, startMinute, startSecond);

    const endDate = new Date();
    endDate.setHours(endHour, endMinute, endSecond);
    if (
      startDate.getTime() < now.getTime() &&
      endDate.getTime() > now.getTime()
    ) {
      console.log("当前时间段可预约");
      setIsBook(true);
    } else {
      message.error("当前时间段不可预约");
      setIsBook(false);
    }
  };
  //签到
  const sighin = async () => {
    await userSign({ signId });

    message.success("签到成功");
  };
  //获取用户签到信息
  const getSign = async () => {
    const res: any = await getSignInfo();
    setSignId(res?.id);
  };
  useEffect(() => {
    getRoomDetail();
    getReview();
    getSign();
  }, []);
  useEffect(() => {
    handleIsBook(room);
  }, [room]);
  return (
    <>
      <BookingSiteForm
        isOpen={isOpen}
        onCancel={onCancel}
        onConfirm={onConfirm}
        onChange={changeDate}
      ></BookingSiteForm>
      <NavBar></NavBar>
      <div className="rd-ctn">
        <div className="top">
          <img src={`${COMURL}${room?.roomPhoto}`} alt="" className="top-img" />
        </div>
        <div className="content">
          <div className="left-ctn">
            <p className="status-title">
              <span className="status-title-icon  status-title-icon-one"></span>
              <span>可预约</span>
            </p>
            {/* <p className="status-title">
              <span className="status-title-icon status-title-icon-two"></span>
              <span>已使用</span>
            </p> */}
            <p className="status-title">
              <span className="status-title-icon status-title-icon-three"></span>
              <span>已使用</span>
            </p>
            <p className="status-title">
              <Button style={{ width: 100, marginTop: 60 }} onClick={sighin}>
                签到
              </Button>
            </p>
          </div>
          <div className="right-ctn">
            <div className="right-ctn-top">
              <div className="right-ctn-top-time">
                开放时间:{room?.openTime}
              </div>
              <div className="right-ctn-top-time">
                关闭时间:{room?.closeTime}
              </div>
            </div>
            <div className="right-ctn-botttom">
              {roomSite?.map((item) =>
                item.siteStatus === 0 && isBook ? (
                  <Popconfirm
                    title="温馨提示"
                    description="确定预约该位置吗？"
                    onConfirm={() => handleIsBookingSite(item.id)}
                    okText="确定"
                    cancelText="取消"
                    key={item.id}
                  >
                    <div className="right-ctn-botttom-item-content">
                      <div
                        className="right-ctn-botttom-item"
                        style={{
                          backgroundColor: getRoomSiteStatus(item.siteStatus),
                        }}
                      ></div>
                      <span
                        style={{ display: "flex", justifyContent: "center" }}
                      >
                        {item.siteNumber}
                      </span>
                    </div>
                  </Popconfirm>
                ) : (
                  <div className="right-ctn-botttom-item-content" key={item.id}>
                    <div
                      className="right-ctn-botttom-item"
                      style={{
                        backgroundColor: getRoomSiteStatus(item.siteStatus),
                      }}
                    ></div>
                    <span style={{ display: "flex", justifyContent: "center" }}>
                      {item.siteNumber}
                    </span>
                  </div>
                )
              )}
            </div>
          </div>
        </div>
        <div className="review-ctn">
          <Review
            textareaRef={textareaRef}
            textRef={textRef}
            reviewList={reviewList}
            value={reviewCtn}
            onChange={handleChange}
            onPublish={onPublish}
            handleReply={handleReply}
            handleDel={handleDel}
          ></Review>
        </div>
      </div>
    </>
  );
};
export default RoomDetails;
